import {
	unlinkSync,
} from 'node:fs';
import {
	dirname,
	basename,
	join,
} from 'node:path';
import {
	pathToFileURL,
	fileURLToPath,
} from 'node:url';
import webpack from 'webpack';
import TerserPlugin from 'terser-webpack-plugin';

const __dirname=dirname(fileURLToPath(import.meta.url));

export default function(baseDir,absolutePath){
	const fileBase=`${absolutePath}.timestamp-${Date.now()}`;
	const fileNameTmp=`${fileBase}.cjs`;
	const fileUrl=`${pathToFileURL(fileBase)}.cjs`;
	return new Promise((resolve,reject) => {
		webpack({
			mode:'production',
			context:baseDir,
			entry:absolutePath,
			output:{
				path:dirname(fileNameTmp),
				filename:basename(fileNameTmp),
				library:{
					type:'commonjs2',
					export:'default',
				},
			},
			target:'node18.19',
			//region 模块
			module:{
				rules:[
					{
						test:/\.ts$/,
						use:[
							{
								loader:'ts-loader',
								options:{
									transpileOnly:true,
									compilerOptions:{
										strict:true,
										module:'esnext',
										target:'esnext',
										moduleResolution:'bundler',
										allowJs:true,
										useDefineForClassFields:true,
										importHelpers:true,
										resolveJsonModule:true,
										esModuleInterop:true,
										baseUrl:baseDir,
										sourceMap:false,
									},
								}
							},
						],
					},
				],
			},
			//endregion
			//region 模块解析
			resolve:{
				extensions:[
					'.ts',
					'.js',
				],
				mainFiles:[
					'index',
				],
				modules:[
					join(__dirname,'../node_modules'),
					join(baseDir,'node_modules'),
					'node_modules',
				],
			},
			//endregion
			//region loader模块解析
			resolveLoader:{
				modules:[
					join(__dirname,'../node_modules'),
					join(baseDir,'node_modules'),
					'node_modules',
				],
			},
			//endregion
			//region 优化
			optimization:{
				minimize:false,
				minimizer:[
					new TerserPlugin({
						minify:TerserPlugin.swcMinify,
						extractComments:false,
						terserOptions:{
							ecma:2015,
							compress:{
								keep_infinity:true,
								passes:1,
								reduce_funcs:false,
							},
							format:{
								comments:false,
							},
						}
					}),
				],
				chunkIds:'deterministic',
				concatenateModules:true,
				flagIncludedChunks:true,
				mangleExports:'deterministic',
				moduleIds:'deterministic',
				providedExports:true,
				removeAvailableModules:true,
				runtimeChunk:false,
				sideEffects:true,
				usedExports:true,
			},
			//endregion
		},(err,stats) => {
			//region 错误处理
			if(err){
				console.error(err.stack||err);
				if(err.details){
					console.error(err.details);
				}
				return reject();
			}
			const info=stats.toJson();
			if(stats.hasWarnings()){
				for(const warn of info.warnings){
					console.log(warn.message);
				}
			}
			if(stats.hasErrors()){
				for(const error of info.errors){
					console.log(error.message);
				}
				return reject();
			}
			//endregion
			resolve(new Function('file', 'return import(file)')(fileUrl));
		});
	}).catch((err) => {
		console.error(err);
	}).finally(() => {
		unlinkSync(fileNameTmp);
	});
};
